<template>
  <a-card title="教学资源知识库管理" :bordered="false">
    <div class="action-bar">
      <a-space>
        <a-select
          v-model:value="selectedDatasetId"
          style="width: 200px"
          @change="handleDatasetChange"
          :loading="datasetLoading"
        >
          <a-select-option
            v-for="dataset in datasets"
            :key="dataset.id"
            :value="dataset.id"
          >
            {{ dataset.name }}
          </a-select-option>
        </a-select>
        <a-button type="primary" @click="showUploadModal">
          <template #icon><upload-outlined /></template>
          上传文件
        </a-button>
        <a-button type="primary" @click="showTextModal">
          <template #icon><file-text-outlined /></template>
          添加文本
        </a-button>
        <a-button type="primary" @click="fetchDatasets">
          <template #icon><unordered-list-outlined /></template>
          数据集列表
        </a-button>
          </a-space>
    </div>
    <a-divider />

    <!-- 文档列表 -->
    <a-table
      :columns="columns"
      :data-source="documents"
      :pagination="pagination"
      :loading="loading"
      bordered
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'type'">
          <a-tag :color="record.type === 'file' ? 'blue' : 'green'">
            {{ record.type === 'file' ? '文件' : '文本' }}
          </a-tag>
</template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <a-button size="small" danger @click="handleDeleteDocument(record)">删除</a-button>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 文件上传模态框 -->
    <a-modal
      v-model:visible="uploadVisible"
      title="上传文件到知识库"
      @ok="handleUpload"
      :confirm-loading="uploading"
    >
      <a-upload
        v-model:file-list="fileList"
        :before-upload="beforeUpload"
        :max-count="6"
      >
        <a-button>
          <upload-outlined />
          选择文件
        </a-button>
      </a-upload>
    </a-modal>

    <!-- 文本添加模态框 -->
    <a-modal
      v-model:visible="textVisible"
      title="添加文本到知识库"
      @ok="handleTextUpload"
      :confirm-loading="textUploading"
    >
      <a-form layout="vertical">
        <a-form-item label="文档名称">
          <a-input v-model:value="textName" placeholder="请输入文档名称" />
        </a-form-item>
        <a-form-item label="内容">
          <a-textarea
            v-model:value="textContent"
            placeholder="请输入文本内容"
            :rows="6"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script>
import { UploadOutlined, FileTextOutlined, UnorderedListOutlined } from '@ant-design/icons-vue'
import { message, Select } from 'ant-design-vue'
import axios from 'axios'

export default {
  components: {
    UploadOutlined,
    FileTextOutlined,
    UnorderedListOutlined,
    'a-select': Select,
    'a-select-option': Select.Option
  },
  data() {
    return {
      BASE_URL: 'http://localhost/v1',
      API_KEY: 'dataset-N4DMKSiyyGF92JwpRLtTRp64',
      DATASET_ID: '',
      
      datasets: [],
      selectedDatasetId: '',
      datasetLoading: false,
      
      fileList: [],
      uploading: false,
      
      textName: '',
      textContent: '',
      textUploading: false,

      documents: [],
      loading: false,
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showSizeChanger: true
      },
      
      uploadVisible: false,
      textVisible: false,
      
      columns: [
        { title: '文档名称', dataIndex: 'name', key: 'name' },
        { title: '类型', key: 'type', width: 100 },
        {
          title: '创建时间',
          dataIndex: 'created_at',
          key: 'created_at',
          width: 180,
          customRender: ({ text }) => {
            return new Date(text * 1000).toLocaleString()
          }
        },
        { title: '操作', key: 'action', width: 120 }
      ],
      apiConfig: {
        baseUrl: 'http://localhost:8000',
        endpoints: {
          updates: '/api/updates/'
        }
      }
    }
  },
  methods: {
    async recordUpdate(action, target, details = '') {
      try {
        const message = `${action === 'add' ? '添加' : action === 'delete' ? '删除' : '更新'}了${target}: ${details}`;
        await axios.post(this.apiConfig.baseUrl + this.apiConfig.endpoints.updates, {
          message,
        });
      } catch (error) {
        console.error('记录更新日志失败:', error);
      }
    },
    showUploadModal() {
      this.uploadVisible = true
      this.fileList = []
    },
    showTextModal() {
      this.textVisible = true
      this.textName = ''
      this.textContent = ''
    },
    beforeUpload(file) {
      this.fileList = [file]
      return false
    },
    async handleUpload() {
      if (this.fileList.length === 0) {
        message.warning('请选择文件')
        return
      }

      this.uploading = true
      const formData = new FormData()
      const file = this.fileList[0].originFileObj || this.fileList[0]
      formData.append('file', file)
      formData.append(
        'data',
        JSON.stringify({
          indexing_technique: "high_quality",
          process_rule: {
            mode: "custom",
            rules: {
              pre_processing_rules: [
                { id: "remove_extra_spaces", enabled: true },
                { id: "remove_urls_emails", enabled: true }
              ],
              segmentation: {
                separator: "###",
                max_tokens: 500
              }
            }
          }
        })
      )
      try {
        const response = await axios.post(
          `${this.BASE_URL}/datasets/${this.DATASET_ID}/document/create-by-file`,
          formData,
          {
            headers: {
              Authorization: `Bearer ${this.API_KEY}`,
              'Content-Type': 'multipart/form-data'
            }
          }
        )
        await this.recordUpdate('add', '知识库文件', file.name)
        message.success('文件上传成功')
        this.uploadVisible = false
      this.fetchDatasets()
      } catch (error) {
        console.error('上传失败详情:', error.response?.data || error.message)
        message.error(`上传失败: ${error.response?.data?.message || error.message}`)
      } finally {
        this.uploading = false
    }
  },
    async handleTextUpload() {
      if (!this.textContent) {
        message.warning('请输入文本内容')
        return
      }
      this.textUploading = true
      try {
        await axios.post(
          `${this.BASE_URL}/datasets/${this.DATASET_ID}/document/create-by-text`,
          {
            name: this.textName || '未命名文档',
            text: this.textContent,
            indexing_technique: 'high_quality',
            process_rule: { mode: 'automatic' }
          },
          {
            headers: {
              Authorization: `Bearer ${this.API_KEY}`,
              'Content-Type': 'application/json'
  }
}
        )
        await this.recordUpdate('add', '知识库文本', this.textName || '未命名文档')
        message.success('文本上传成功')
        this.textVisible = false
        this.fetchDatasets()
      } catch (error) {
        message.error('文本上传失败')
        console.error(error)
      } finally {
        this.textUploading = false
      }
    },
    async fetchDatasets() {
      try {
        this.loading = true
        const response = await axios.get(
          `${this.BASE_URL}/datasets/${this.DATASET_ID}/documents`,
          {
            headers: {
              Authorization: `Bearer ${this.API_KEY}`
            },
            params: {
              page: this.pagination.current,
              limit: this.pagination.pageSize
            }
          }
        )
        this.documents = response.data.data || []
        this.pagination.total = response.data.total || 0
      } catch (error) {
        message.error('获取数据集列表失败')
        console.error(error)
      } finally {
        this.loading = false
      }
    },
    async handleDeleteDocument(record) {
      try {
        await axios.delete(
          `${this.BASE_URL}/datasets/${this.DATASET_ID}/documents/${record.id}`,
          {
            headers: {
              Authorization: `Bearer ${this.API_KEY}`
            }
          }
        )
        await this.recordUpdate('delete', '知识库文档', record.name)
        message.success('文档删除成功')
        this.fetchDatasets()
      } catch (error) {
        message.error('文档删除失败')
        console.error(error)
      }
    },
    async fetchDatasetsList() {
      try {
        this.datasetLoading = true
        const response = await axios.get(
          `${this.BASE_URL}/datasets`,
          {
            headers: {
              Authorization: `Bearer ${this.API_KEY}`
  },
            params: {
              page: 1,
              limit: 100
  }
}
        )
        this.datasets = response.data.data || []
        if (this.datasets.length > 0) {
          this.selectedDatasetId = this.datasets[0].id
          this.DATASET_ID = this.datasets[0].id
        }
      } catch (error) {
        message.error('获取知识库列表失败')
        console.error(error)
      } finally {
        this.datasetLoading = false
      }
    },
    handleDatasetChange(value) {
      this.selectedDatasetId = value
      this.DATASET_ID = value
      this.fetchDatasets()
    }
  },
  mounted() {
    this.fetchDatasetsList().then(() => {
      if (this.datasets.length > 0) {
        this.fetchDatasets()
      }
    })
  }
}
</script>

<style scoped>
.action-bar {
  margin-bottom: 16px;
}
</style>

